/*
 * @Author: 邱狮杰
 * @Date: 2021-05-15 10:34:38
 * @LastEditTime : 2021-05-20 17:08:16
 * @FilePath     : /wedding-dress-selection/src/page/selectionRecommendation/index.tsx
 * @Description: 婚礼选款
 */
import { useState, MouseEvent, FC } from 'react'
import { useHistory } from 'react-router-dom'
import { message } from 'antd'
import OperactionButton from './components/button/index'
import Design from './components/designList/index'
import { useGetOpenid } from '../../hook/index'
import Button from '../../components/button/index'
import FlexAuxiliary from '../../components/layout/flexAuxiliarys/index'
import Mask from '../../components/layout/mask/index'
import Alert from '../../components/alert/index'
import { useEdit } from './hooks/edit'
import { useLikeForReducer, useUserInfoForReducer } from '../../hook/index'
import { getLocal, sendLikeRequest } from '../../utils/index'

import './index.scss'
import { OPENID } from '../../reducer/userInfo'

type Props = {
  onProxyAlertMask: () => void
  onProxyBack: () => void
}

export type RefInterface = {
  isDelete: (isTrue: boolean) => void
}

const SelectionRecommendation: FC<Props> = ({ onProxyAlertMask, onProxyBack }) => {
  const his = useHistory()
  useGetOpenid(() => {})
  const { likeState, likeDispatch } = useLikeForReducer()
  const { userInfoState, userInfoDispatch } = useUserInfoForReducer()
  const [alert, setAlert] = useState<boolean>(false)
  const [showButtomButtonOperaction, setShowButtomButtonOperaction] = useState<boolean>(true)
  const [edit, setEdit] = useState<boolean>(false)
  const [style] = useEdit<boolean>(edit)

  // 切换编辑状态handler 无副作用
  function switchEditStateNoEffect() {
    setEdit(!edit)
  }
  // function filterLikes() {
  //   return Array.from(
  //     new Set(
  //       likeState
  //         .filter(likeItem => !likeItem.check)
  //         .map(likeMap => likeMap.id.toString())
  //         .concat(...userInfoState.likes)
  //     )
  //   ).join(',')
  // }
  // 切换编辑状态handler 有副作用
  function switchEdit() {
    if (!edit) {
      // 编辑状态下切换状态 无副作用
      switchEditStateNoEffect()
      likeDispatch({ type: 'editChange', data: !edit })
      likeDispatch({ type: 'editCheck', data: false })
    } else {
      // 删除状态会有副作用
      // 并没有删除项，直接切换状态为编辑,无副作用
      const check = likeState.some(item => item.check)
      if (!check) {
        likeDispatch({ type: 'editChange', data: !edit })
        switchEditStateNoEffect()
        setShowButtomButtonOperaction(true)
        return
      }
      // 显示alert 弹窗询问是否删除
      else {
        setAlert(!alert)
      }
    }
    setShowButtomButtonOperaction(false)
  }

  // 选中单个
  function SelectAnItem(e: MouseEvent<HTMLDivElement, globalThis.MouseEvent>, index: number) {
    const cur = likeState[index].check
    likeDispatch({ type: 'itemEdit', data: { index, state: !cur } })
  }

  async function isDelete(isTrue: boolean) {
    const backup = userInfoState.likes
    if (isTrue) {
      // 删除
      likeDispatch({ type: 'delete' })
      likeState
        .filter(likeItem => likeItem.check)
        .map(likeMap => likeMap.id)
        .forEach(item => {
          const idx = backup.findIndex(i => i === item.toString())
          if (!idx) backup.shift()
          else backup.splice(1, idx)
        })
      userInfoDispatch({ type: 'editLikes', data: backup })
      switchEditStateNoEffect()
      const [err, res] = await sendLikeRequest(userInfoState.invitationId as string, userInfoState.openId || (getLocal(OPENID) as string), backup.join(','))
      if (!err) {
        if (res.code === 200) message.success('删除成功')
      }
    } else {
      // 取消
      likeDispatch({ type: 'editCheck', data: false })
      switchEditStateNoEffect()
    }
    setAlert(!alert)
    likeDispatch({ type: 'editChange', data: !edit })
    setShowButtomButtonOperaction(true)
  }

  async function end() {
    const [err, res] = await sendLikeRequest(userInfoState.invitationId as string, userInfoState.openId || (getLocal(OPENID) as string), userInfoState.likes.join(','))
    if (!err) {
      if (res.code === 200) his.push('/end')
    }
  }

  return (
    <div className='containerSelect'>
      <div className='layout'>
        <h3>我心仪的</h3>
        <OperactionButton style={style} onProxyClick={switchEdit} content={edit ? '删除' : '编辑'} />
      </div>
      <Design designConf={likeState} onProxyCheckClick={SelectAnItem} />
      {/*/!*style={{bottom: "5%", position: "fixed", left: '0'}}*!/*/}
      {showButtomButtonOperaction && (
        <FlexAuxiliary style={{ bottom: '2%', position: 'fixed', left: '0' }}>
          <Button onProxyClick={() => his.push('/main')} style={{ background: 'rgba(255,255,255,0.8)', color: '#222', border: '1px solid #f1f1f1' }} content='继续选纱' />
          <Button onProxyClick={end} content='结束选纱' />
        </FlexAuxiliary>
      )}
      <Mask show={alert} />
      <Alert show={alert} onProxyClick={isDelete} />
    </div>
  )
}
export default SelectionRecommendation
